package com.zhitong.money.exception;

import com.zhitong.money.entity.AjaxResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * Description:全局异常处理
 * date: 2021/1/25 21:20
 *
 * @author Andy Zhang
 * @since JDK 1.8
 */
@Slf4j
@ControllerAdvice(basePackages = "com.zhitong.money.controller")
public class GlobalExceptionHandler {



    @ExceptionHandler(value = RepeatException.class)
    @ResponseBody
    public AjaxResponse repeatException(){
        return AjaxResponse.fail("信息重复!请重新填写!");
    }

    @ExceptionHandler(value = AddException.class)
    @ResponseBody
    public AjaxResponse addException(){
        return AjaxResponse.fail("添加失败!请稍后尝试!");
    }

    @ExceptionHandler(value = UpdateException.class)
    @ResponseBody
    public AjaxResponse updateException(){
        return AjaxResponse.fail("更新失败!请稍后尝试");
    }

    @ExceptionHandler(value = DeleteException.class)
    @ResponseBody
    public AjaxResponse deleteException(DeleteException e){
        log.error("====>删除时异常:"+e.getMessage());
        return AjaxResponse.fail("删除失败!请稍后尝试");
    }

    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public AjaxResponse nullException(NullPointerException e){
        log.warn("====>查询为空异常:"+e.getMessage());
        return AjaxResponse.fail("暂无任何数据");
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public AjaxResponse exception(Exception e){
        log.error("====>运行时异常:"+e.getMessage());
        return AjaxResponse.fail("服务器异常!请稍后尝试!");
    }

    @ExceptionHandler(value = AuthorizationException.class)
    @ResponseBody
    public AjaxResponse authException(AuthorizationException e) {
        AjaxResponse ajaxResponse;
        String message = e.getMessage();
        String msg=message.substring(message.indexOf("[")+1,message.indexOf("]"));
        //判断是角色错误还是权限错误
        if (message.contains("role")) {
            ajaxResponse=AjaxResponse.aFail( "对不起，您没有" + msg + "角色");
        } else if (message.contains("permission")) {
            ajaxResponse=AjaxResponse.aFail( "对不起，您没有" + msg + "权限");
        } else {
            ajaxResponse=AjaxResponse.aFail( "对不起，您的权限有误");
        }
        return ajaxResponse;
    }

}
